<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>管理员个人信息</span>
            </div>
        </template>

        <el-form ref="adminInfoForm" :model="adminInfo" :rules="rules" label-width="120px" label-position="right"
            status-icon>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="adminInfo.email" placeholder="邮箱" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="adminInfo.phone" placeholder="电话" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="用户角色" prop="coreRole">
                        <el-input v-model="adminInfo.coreRole" readonly placeholder="用户角色" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="在线状态" prop="onlineStatus">
                        <el-input v-model="adminInfo.onlineStatus" readonly placeholder="在线状态" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="创建时间" prop="createdAt">
                        <el-input v-model="adminInfo.createdAt" readonly placeholder="创建时间" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="更新时间" prop="updatedAt">
                        <el-input v-model="adminInfo.updatedAt" readonly placeholder="更新时间" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item>
                <el-button type="primary" @click="submitForm">保存修改</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button @click="fetchAdminInfo">刷新信息</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { selectUser } from '@/api/user'; // 假设你有一个 API 来获取管理员信息
import { updateUser } from '@/api/userManger';
import { useRouter } from 'vue-router'; // 引入 useRouter

const userDO = reactive({
        userId: localStorage.getItem('id'), // 假设你有一个 API 来获取管理员信息,
        email: '',
        phone: '',
      });

export default {
    setup() {
        const router = useRouter();
        const adminInfo = reactive({
            email: '',
            phone: '',
            coreRole: '',
            onlineStatus: null,
            createdAt: '',
            updatedAt: ''
        });

        // 表单规则
        const rules = reactive({
            email: [
                { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
            ],
            phone: [
                { required: true, message: '请输入电话号码', trigger: 'blur' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
            ]
        });

        // 表单引用
        const adminInfoForm = ref(null);
        
        // 获取管理员信息
        const fetchAdminInfo = async () => {
            
            try {
                // 这里使用 fetch 模拟从后端获取数据，实际项目中应该替换为 axios 或其他 HTTP 请求工具
                const response = await selectUser(localStorage.getItem('id'));
                // alert(localStorage.getItem('role'));

                // 整合信息
                if (response.code === '000') {
                    const { userDO } = response.data;
                    adminInfo.email = userDO.email;
                    adminInfo.phone = userDO.phone;
                    adminInfo.coreRole = userDO.coreRole || '未设置';
                    adminInfo.onlineStatus = userDO.onlineStatus || 0;
                    adminInfo.createdAt = userDO.createdAt;
                    adminInfo.updatedAt = userDO.updatedAt;
                }
            } catch (error) {
                console.error('获取管理员信息失败:', error);
                alert('获取管理员信息失败，请稍后再试');
            }
        };
        if (localStorage.getItem('role')) {
            // alert(localStorage.getItem('role'));
            if (localStorage.getItem('role') === 'doctor') {
                router.push({ name: 'profileDoctor' });
            } else if (localStorage.getItem('role') === 'patient') {
                router.push({ name: 'profilePatient' });
            }
        }

        // 提交表单
        const submitForm = () => {
            adminInfoForm.value.validate( async (valid) => {
                if (valid) {
                    userDO.userId = localStorage.getItem('id');
                    userDO.email = adminInfo.email;
                    userDO.phone = adminInfo.phone;
                    alert('提交成功!');
                    // 这里可以添加提交到后端的逻辑
                
                    
                        // 这里使用 fetch 模拟从后端获取数据，实际项目中应该替换为 axios 或其他 HTTP 请求工具
                        const response = await updateUser(userDO);
                    if (response.code === "000") 
                        alert("更新成功！");

                } else {
                    console.log('表单验证失败');
                    return false;
                }
            });
        };

        // 重置表单
        const resetForm = () => {
            adminInfoForm.value.resetFields();
        };

        // 页面加载时获取管理员信息
        onMounted(() => {
            fetchAdminInfo();
        });

        return {
            adminInfo,
            rules,
            adminInfoForm,
            submitForm,
            resetForm,
            fetchAdminInfo
        };
    }
}
</script>

<style scoped>
.box-card {
    max-width: 1000px;
    margin: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

h3 {
    margin-top: 20px;
    margin-bottom: 15px;
    color: #606266;
}

.el-row {
    margin-bottom: 15px;
}
</style>